package com.youlai.system.common.util;

import com.youlai.system.model.entity.AnalyzeData;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


public class DataUtils {

        public static AnalyzeData analyzeData(int[] data) {
            // 计数
            int count = data.length;

            // 最小值和最大值
            Arrays.sort(data);
            int min = data[0];
            int max = data[count - 1];

            // 总和
            int sum = Arrays.stream(data).sum();

            // 平均值
            double mean = (double) sum / count;

            // 中位数
            double median;
            if (count % 2 == 0) {
                median = (data[count / 2 - 1] + data[count / 2]) / 2.0;
            } else {
                median = data[count / 2];
            }

            // 众数
            Map<Integer, Integer> frequencyMap = new HashMap<>();
            for (int num : data) {
                frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
            }
            int mode = frequencyMap.entrySet().stream()
                    .max(Map.Entry.comparingByValue())
                    .map(Map.Entry::getKey)
                    .orElse(0);

            // 范围
            int range = max - min;

            // 方差
            double variance = Arrays.stream(data).mapToDouble(n -> Math.pow(n - mean, 2)).average().orElse(0.0);

            // 标准差
            double stdDeviation = Math.sqrt(variance);

            // 创建 JSON 对象并填充结果
            return new AnalyzeData(count, min, max, sum, mean, median, mode, range, variance, stdDeviation);
        }

}
